/*
 * Copyright (C) 2019 Beijing GAGO Technology Ltd.
 */

package com.logos.common.source.network.interceptor;

import android.util.Base64;

import com.google.gson.JsonObject;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * @author Young Ken
 */
public class DownloadFileInterceptor implements Interceptor {
    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request request = chain.request()
                .newBuilder()
                .addHeader("Content-Type", "application/octet-stream")
                .build();

        Response response = chain.proceed(request);
        if (response.body() != null && response.body().contentType() != null) {
            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
            byte[] bytes = response.body().source().readByteArray();
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("code", response.code());
            jsonObject.addProperty("bytes", Base64.encodeToString(bytes,Base64.DEFAULT));
            ResponseBody responseBody = ResponseBody.create(mediaType, jsonObject.toString());
            return response.newBuilder().body(responseBody).build();
        } else {
            return response;
        }
    }

    /**
     * crate UploadFileInterceptor
     *
     * @return UploadFileInterceptor
     */
    public static DownloadFileInterceptor create() {
        return new DownloadFileInterceptor();
    }
}
